/*
 * @Author: 41
 * @Date: 2022-02-20 12:38:19
 * @LastEditors: YWY
 * @LastEditTime: 2022-03-07 08:26:26
 * @Description: 
 */
import axios from 'axios'
// import { mainStore } from "../store/index.js";
// const main = mainStore();

// 创建axios,赋给变量service
const BASEURL = process.env.NODE_ENV === 'production' ? '' : '/api';
export let cancel = null

const service = axios.create({
  // baseURL: 'http://localhost:8000',
  baseURL: 'http://xylt.ruanmeng.love/api',
  timeout: 5000,
})


// 添加请求拦截器
service.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  if (/sugrec/.test(config.url)) {
    // config.baseURL = "http://localhost:3000/"
    config.baseURL = "http://xylt.ruanmeng.love/"
  }

  if (localStorage.getItem('Authorization')) {
    config.headers.Authorization = localStorage.getItem('Authorization');
  }
  console.log(config)
  //判断是否需要进行防抖
  if (/article/.test(config.url) || /sugrec/.test(config.url)) {
    config.cancelToken = new axios.CancelToken((c) => {
      cancel = c;
    })
  }
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
service.interceptors.response.use(
  // 对响应数据做点什么
  // return response;
  response => {
    let data = response.data
    let status = response.status
    if (status === 200) {
      return Promise.resolve(data)
    } else if (status === 301) {
      Message.error({ message: '请先登录!' })
      localStorage.removeItem('Authorization');
      router.replace({
        path: '/login'
      })
      return
    } else {
      return Promise.reject(response)
    }
  }, error => {
    // 对响应错误做点什么
    // console.log(error)
    console.log('服务器返回错误响应')
    return Promise.reject(error);
  });


export default service
